package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.IStatementService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Override

    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }


    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    @Transactional
    public void deploy(String path, String bpmnType, String info) throws FileNotFoundException {
//          Deployment deploy = null;
            //1.根据path(路径)找到流程文件
            File bpmnFile = new File(SystemConfig.getProfile(), path);
            //2.把流程文件部署到Activiti中
        System.out.println(new FileInputStream(bpmnFile).toString());
            Deployment deploy = repositoryService.createDeployment()
                    .addInputStream(path,new FileInputStream(bpmnFile))
                    .deploy();
            //3.根据生成部署对象,流程定义对象,封装BpmnInfo信息
            BpmnInfo bpmnInfo = new BpmnInfo();
            //什么类型的审核
            bpmnInfo.setBpmnType(bpmnType);
            //备注信息
            bpmnInfo.setInfo(info);
            //部署ID
            bpmnInfo.setDeploymentId(deploy.getId());
            //部署时间
            bpmnInfo.setDeployTime(new Date());
            //获取流程定义对象
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .deploymentId(deploy.getId())
                    .singleResult();
            bpmnInfo.setActProcessId(processDefinition.getId());
            bpmnInfo.setActProcessKey(processDefinition.getKey());
            bpmnInfo.setBpmnName(processDefinition.getName());
            //4.保存到数据库中
            bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public void delete(Long id) {
        //1.根据id查询bpmn对象
        BpmnInfo bpmnInfo = this.get(id);
        //2.删除bpmnInfo对象
        bpmnInfoMapper.deleteByPrimaryKey(id);
        //TODO
        //查询目前这个流程定义正在运行的流程实例
        //把流程实例关联的BusinessKey找到业务对象
        //3.获取流程定义对象
        ProcessDefinition processDefinition =repositoryService
                .createProcessDefinitionQuery()
                .deploymentId(bpmnInfo.getDeploymentId())
                .singleResult();
        //4.删除activiti流程定义对象
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(), true);
        //5.把服务器上的文件删除
        String resourceName = processDefinition.getResourceName();
        File file = new File(SystemConfig.getProfile(), resourceName);
        if(file.exists()){
            file.delete();
        }
    }

    @Override
    public InputStream getResoucceByType(String deploymentId, String type) {
        ProcessDefinition definition = repositoryService
                .createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
        if("xml".equalsIgnoreCase(type)){
            return repositoryService.getResourceAsStream(deploymentId,definition.getResourceName());
        }else if("png".equalsIgnoreCase(type)){
            BpmnModel model = repositoryService.getBpmnModel(definition.getId());
            //DefaultProcessDiagramGenerator(默认流程图生成器)
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            InputStream inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
            return inputStream;
        }
        return null;
    }

    @Override
    public BpmnInfo queryByType(String carPackage) {
        return bpmnInfoMapper.queryByType(carPackage);
    }
}